import { getLiveList, like, view } from "@/api/modules/live";
import cloneDeep from "lodash/cloneDeep";
const livePlayer = requirePlugin("live-player-plugin");
import {
  Component,
  Vue
} from "vue-property-decorator";
@Component({})
export default class LiveMix extends Vue {

  liveList: Array<any> = [];
  current: number = 1;
  total: number = 0
  isFetch: boolean = false
  loading: boolean = false

  timer: number
  // 跳转直播间
  onGotoLive(e) {
    const roomId = e.currentTarget.dataset.room_id;
    const id = e.currentTarget.dataset.id;
    let viewCount = e.currentTarget.dataset.count;
    try {
      viewCount = parseInt(viewCount, 10) + 1;
    } catch (err) {
      viewCount = 1;
      console.log(err);
    }
    view({ id, viewCount }).then(() => this.fetchLiveList());
    uni.navigateTo({
      url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}`,
    });
  }

  // 点赞
  onClickLike(e) {
    const roomId = e.currentTarget.dataset.room_id;
    const id = e.currentTarget.dataset.id;
    let likeCount = e.currentTarget.dataset.count;
    try {
      likeCount = parseInt(likeCount, 10) + 1;
    } catch (err) {
      likeCount = 1;
    }
    const liveList = this.liveList;
    liveList.forEach(v => {
      if (v.roomId + "" === roomId + "") {
        v.clickLike = true;
      }
    });
    this.liveList = liveList
    setTimeout(() => {
      liveList.forEach(v => {
        if (v.roomId + "" === roomId + "") {
          v.clickLike = false;
          v.likeCount = likeCount;
        }
      });
      this.liveList = liveList
      like({ id, likeCount });
    }, 400);
  }

  /* 获取直播列表 */
  async fetchLiveList(current = 1, isMore = false) {
    this.isFetch = isMore ? false : true
    this.loading = isMore ? true : false
    const res = await getLiveList({
      current,
      size: 20,
    });
    this.liveList = isMore
      ? [...this.liveList, ...(res.list || [])]
      : res.list
    this.current = res.current
    this.total = res.total
    this.isFetch = false
    this.loading = false
    setTimeout(() => {
      this.updateStatus();
      clearInterval(this.timer);
      this.timer = setInterval(this.updateStatus, 1000 * 60);
    }, 100);
  }

  // 更新直播状态
  async updateStatus() {
    const liveList = cloneDeep(this.liveList);
    const asyncArrs: any[] = liveList.map(v => {
      // eslint-disable-next-line @typescript-eslint/camelcase
      return livePlayer.getLiveStatus({ room_id: v.roomId });
    });
    const arrRes = await Promise.all(asyncArrs);
    this.liveList = cloneDeep(
      liveList.map((v, i) => {
        v.status = arrRes[i].liveStatus;
        return v;
      }),
    )
  }
};
